import pymysql


class MysqlHelper(object):
    """"""
    def __init__(self, host, db, user, password, port=3306, charset="utf8"):
        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        self.charset = charset
        self.connection = None
        self.cursor = None

    def open(self):
        self.connection = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            passwd=self.password,
            db=self.db,
            charset=self.charset)
        self.cursor = self.connection.cursor()

    def close(self):
        self.cursor.close()
        self.connection.close()

    # 增删改
    def cud(self, sql, params):
        try:
            self.open()
            self.cursor.execute(sql, params)
            self.connection.commit()
            self.close()
        except Exception as message:
            print("增删改异常信息为：%s" % message)

    # 查询
    def inquire(self, sql, params):
        try:
            self.open()
            self.cursor.execute(sql, params)
            result = self.cursor.fetchall()
            self.close()
            return result
        except Exception as message:
            print("查询异常信息为：%s" % message)
